<template>
    <v-container>
        <div class="text-center">
            <v-icon size="100" color="blue" class="panda-icon mb-4">mdi-panda</v-icon>
        </div>
        <v-row justify="center" align="center">
            <v-col cols="12">
                <template v-if="isLoggedIn">
                    <v-list>
                        <template v-for="(otp, index) in otpList" :key="index">
                            <v-list-item :class="{
                                'bg-red-lighten-4': otp.owner && otp.owner !== user.realname,
                                'bg-green-lighten-4': !otp.owner || otp.owner === user.realname
                            }" @click="copyOTP(otp)">
                                <v-list-item-title>{{ otp.name }}</v-list-item-title>

                                <v-list-item-subtitle v-if="otp.is_enabled && (!otp.owner || otp.owner === user.username)">
                                    倒计时: {{ otp.countdown }} 秒
                                </v-list-item-subtitle>

                                <v-list-item-subtitle v-if="otp.owner">
                                    当前使用者: {{ otp.owner === user.username ? '当前用户' : otp.owner }}
                                </v-list-item-subtitle>

                                <template v-slot:append v-if="otp.owner === user.realname">
                                    <v-btn icon="mdi-logout" size="small" @click.stop="releaseOTP(otp)"></v-btn>
                                </template>
                            </v-list-item>
                            <v-divider v-if="index < otpList.length - 1"></v-divider>
                        </template>
                    </v-list>
                    <v-pagination v-model="currentPage" :length="totalPages" @update:model-value="fetchOtpList"
                        class="mt-4"></v-pagination>
                    <v-btn block color="secondary" class="mt-4" @click="changePassword">修改密码</v-btn>
                    <v-btn block color="secondary" class="mt-4" @click="logout">登出</v-btn>
                    <template v-if="isAdmin">
                        <v-btn block color="primary" class="mt-4" @click="manageUsers">用户管理</v-btn>
                        <v-btn block color="primary" class="mt-4" @click="manageOtps">验证码管理</v-btn>
                        <!-- <v-btn block color="primary" class="mt-4" @click="managePermissions">授权管理</v-btn> -->
                    </template>
                </template>
                <template v-else>
                    <v-btn block color="primary" class="mb-4" @click="goToLogin">登录</v-btn>
                    <v-btn block color="secondary" class="mb-4" @click="register">注册</v-btn>
                    <v-btn block color="info" @click="about">关于</v-btn>
                </template>
            </v-col>
            <v-snackbar v-model="snackbar" :timeout="2000">
                {{ snackbarText }}
            </v-snackbar>
        </v-row>
    </v-container>
</template>

<script>
import { getUserCodeList, generateCode, releaseCode } from '@/service/api';

export default {
    name: 'Home',
    data() {
        return {
            isLoggedIn: false,
            isAdmin: false,
            user: null,
            otpList: [],
            intervalId: null,
            fetchIntervalId: null,
            snackbar: false,
            snackbarText: '',
            currentPage: 1,
            totalPages: 1,
            pageSize: 5
        }
    },
    created() {
        // 检查登录状态
        this.isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
        if (this.isLoggedIn) {
            this.user = JSON.parse(localStorage.getItem("userProfile"));
            this.fetchOtpList();
            this.startCountdown()
            this.startFetchInterval();
        }
        this.isAdmin = localStorage.getItem('isAdmin') === 'true'
    },
    beforeUnmount() {
        this.stopCountdown()
        this.stopFetchInterval()
    },
    methods: {
        async fetchOtpList() {
            try {
                const response = await getUserCodeList(this.currentPage, this.pageSize);
                if (response.code === 200) {
                    this.otpList = response.data.items.map(item => ({
                        ...item,
                        countdown: 30,
                    }));
                    this.totalPages = Math.ceil(response.data.total / this.pageSize);
                } else {
                    console.error('Failed to fetch OTP list:', response.message);
                }
                console.log(this.otpList);
            } catch (error) {
                console.error('Error fetching OTP list:', error);
            }
        },
        startFetchInterval() {
            this.fetchIntervalId = setInterval(() => {
                this.fetchOtpList();
            }, 30000); // 每30秒重新获取一次验证码列表
        },
        stopFetchInterval() {
            if (this.fetchIntervalId) {
                clearInterval(this.fetchIntervalId);
            }
        },
        goToLogin() {
            this.$router.push('/login')
        },
        changePassword() {
            this.$router.push('/password')
        },
        register() {
            this.$router.push('/register')
        },
        addNewOTP() {
            console.log('添加新的OTP')
            // 这里可以添加新OTP的逻辑
        },
        about() {
            this.$router.push('/about')
        },
        logout() {
            localStorage.removeItem('isLoggedIn')
            this.isLoggedIn = false
            this.stopCountdown()
            this.stopFetchInterval()
            console.log('已登出')
        },
        startCountdown() {
            const updateCountdown = () => {
                const now = new Date();
                const seconds = now.getSeconds();
                let nextReset = seconds < 30 ? 30 - seconds : 60 - seconds;

                this.otpList.forEach(otp => {
                    if (otp.is_enabled && (!otp.owner || otp.owner === this.user.username)) {
                        otp.countdown = nextReset;
                    }
                });
            };

            updateCountdown();

            this.intervalId = setInterval(() => {
                this.otpList.forEach(otp => {
                    if (otp.is_enabled && (!otp.owner || otp.owner === this.user.username)) {
                        otp.countdown -= 1;
                        if (otp.countdown <= 0) {
                            updateCountdown();
                        }
                    }
                });
            }, 1000);
        },
        stopCountdown() {
            if (this.intervalId) {
                clearInterval(this.intervalId)
            }
        },
        copyGenerateOTP(otp) {
            generateCode(otp.id).then(response => {
                const generatedCode = response.data.otp;
                navigator.clipboard.writeText(generatedCode).then(() => {
                    this.snackbarText = `验证码 ${otp.name} 已复制到剪贴板`;
                    this.snackbar = true;
                    if (!otp.owner) {
                        otp.owner = this.user.username;
                    }
                    // 立即更新列表
                    this.fetchOtpList();
                }).catch(err => {
                    console.error('复制失败:', err);
                    this.snackbarText = '复制失败，请重试';
                    this.snackbar = true;
                });
            }).catch(err => {
                console.error('生成验证码失败:', err);
                this.snackbarText = '生成验证码失败，请重试,错误：' + err;
                this.snackbar = true;
            });
        },
        copyOTP(otp) {

            if (!otp.is_enabled) {
                return;
            }
            if (!otp.owner) {
                this.copyGenerateOTP(otp);
                return;
            }
            if (otp.owner !== this.user.realname) {
                this.snackbarText = '无法复制验证码：验证码已被禁用或被其他用户占用';
                this.snackbar = true;
                return;
            }
            this.copyGenerateOTP(otp);
        },
        releaseOTP(otp) {
            if (otp.owner === this.user.realname) {
                releaseCode(otp.id).then(() => {
                    this.fetchOtpList();
                    otp.owner = null;
                    this.snackbarText = `验证码 ${otp.name} 已释放`;
                    this.snackbar = true;
                }).catch(err => {
                    console.error('释放验证码失败:', err);
                    this.snackbarText = '释放验证码失败，请重试';
                    this.snackbar = true;
                });
            }
        },
        manageUsers() {
            this.$router.push('/user-management');
        },
        manageOtps() {
            this.$router.push('/code')
        },
        goToOtpManagement() {
            this.$router.push('/otp-management');
        },
        goToAddOtp() {
            this.$router.push('/add-otp');
        }
    }
}
</script>

<style scoped>
.v-list-item {
    margin-bottom: 8px;
    cursor: pointer;
}

.v-list-item:disabled {
    cursor: not-allowed;
    opacity: 0.6;
}

.panda-icon {
    margin-top: -20px;
}

.v-application .v-container {
    background: linear-gradient(to bottom, #ffffff, #e6f2ff);
    min-height: 100vh;
    height: 100vh;
    padding-top: 20px;
    padding-bottom: 20px;
    display: flex;
    flex-direction: column;
}
</style>